package com.sq.partner.manager.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.GatewayCache;
import com.sq.partner.manager.common.MonitorAppCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.GatewayConfig;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.IGatewayConfigService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
@Controller
@RequestMapping(value="/systemManager")
public class ConfigController {
    private static Logger logger = LogUtil.getLog(ConfigController.class);
    
	@Autowired
	private  IGatewayConfigService  gatewayConfigService;
	@Autowired
	private LoginController loginController;
	/**
	 * 展示系统配置页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/systemConfig")
	public String config(HttpServletRequest request) throws Exception{
		return "systemManager/systemConfig";
	}
	/**
	 * 查询所有
	 * @param gatewayConfig
	 * @return 
	 * @throws Exception
	 */
	@RequestMapping(value="/queryList")
	@ResponseBody
	public Page<GatewayConfig> queryList () throws Exception {
		List<GatewayConfig> list = gatewayConfigService.queryConfigList(new GatewayConfig());
		Page page = new Page();
		page.setData(list);
		return  page;
	}
	/**
	 * 根据名称查询
	 * @param configName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getConfigByName")
	@ResponseBody
	public  GatewayConfig  getConfigByName (String configName) throws Exception {
		return gatewayConfigService.queryConfigByName(configName);
	}
	/**
	 * 增加系统配置
	 * @param configName
	 * @param configValue
	 * @param configDesc
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/addConfig")
	@ResponseBody
	public  Result  addConfig(HttpServletRequest req,GatewayConfig  gatewayConfig,String configName,String configValue,String configDesc) throws Exception{
		if(StrUtil.isEmpty(configName)){
			return Result.error("系统配置名称不能为空");
		}else if(configName.length()>30){
			return Result.error("长度不能超过30个字符");
		}else if(StrUtil.isEmpty(configValue)){
			return Result.error("系统配置值不能为空");
		}else if(configValue.length()>200){
			return Result.error("长度不能超过200个字符");
		}else if(StrUtil.isEmpty(configDesc)){
			return Result.error("系统配置描述不能为空");
		}else if(configDesc.length()>40){
			return Result.error("长度不能超过40个字符");
		}
		gatewayConfig.setConfigName(configName);
		gatewayConfig.setConfigValue(configValue);
		gatewayConfig.setConfigDesc(configDesc);
		gatewayConfig.setOperTime(new Date());
		gatewayConfig.setOperUser(((GatewayUser)getSessionUser(req)).getUserid());
		boolean flag = gatewayConfigService.saveConfig(gatewayConfig);
		if(flag){
			GatewayCache.refresh(); 
			return Result.success("添加系统配置成功");
		}else{
			GatewayCache.refresh(); 
			return Result.error("添加系统配置失败");
		}
		
	}
	/**
	 * 修改系统配置 
	 * @param req
	 * @param gatewayConfig
	 * @param configName
	 * @param configValue
	 * @param configDesc
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editConfig")
	@ResponseBody
	public Result editConfig(HttpServletRequest req,GatewayConfig  gatewayConfig,String configName,String configValue,String configDesc) throws Exception{
		if(StrUtil.isEmpty(configName)){
			return Result.error("参数名称不能为空");
		}else if(configName.length()>30){
			return Result.error("参数名称的长度不能超过30个字符");
		}else if(StrUtil.isEmpty(configValue)){
			return Result.error("参数值不能为空");
		}else if(configValue.length()>200){
			return Result.error("参数值的长度不能超过200个字符");
		}else if(StrUtil.isEmpty(configDesc)){
			return Result.error("参数描述不能为空");
		}else if(configDesc.length()>40){
			return Result.error("参数描述的长度不能超过40个字符");
		}
		gatewayConfig.setConfigName(configName);
		gatewayConfig.setConfigValue(configValue);
		gatewayConfig.setConfigDesc(configDesc);
	    gatewayConfig.setOperTime(new Date());
		gatewayConfig.setOperUser(((GatewayUser)getSessionUser(req)).getUserid());
        if(configName.equals("LOGIN_SWITCH_VALUE")){
        	if(!GatewayCache.getCache(configName).equals(configValue)){
         		gatewayConfig.setConfigDesc(configDesc);
         	    gatewayConfig.setOperTime(new Date());
         		gatewayConfig.setOperUser(((GatewayUser)getSessionUser(req)).getUserid());
         	boolean flag1 = gatewayConfigService.updateConfig(gatewayConfig);
              if(flag1)	{
                 GatewayCache.refresh();  
                 return Result.fail("修改参数配置成功，请重新登录");
             }	
        	}else{
         		gatewayConfig.setConfigDesc(configDesc);
         	    gatewayConfig.setOperTime(new Date());
         		gatewayConfig.setOperUser(((GatewayUser)getSessionUser(req)).getUserid());
         		boolean  flag = gatewayConfigService.updateConfig(gatewayConfig);
      			if(flag){
      				GatewayCache.refresh(); 
      				return Result.success("修改参数配置成功");
      			}else{
      				GatewayCache.refresh(); 
      				return Result.error("修改参数配置失败");
      			}
        	}
  	    }else{
  	    	boolean  flag = gatewayConfigService.updateConfig(gatewayConfig);
  			if(flag){
  				GatewayCache.refresh(); 
  				return Result.success("修改参数配置成功");
  			}else{
  				GatewayCache.refresh(); 
  				return Result.error("修改参数配置失败");
  			}
  	    }
		return  null;
	}
	/**
	 * 删除系统配置
	 * @param configName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteConfig")
	@ResponseBody 
	public  Result  deleteConfig(String configName) throws Exception{
		if(configName!=null){
			gatewayConfigService.deleteConfig(configName);
			GatewayCache.refresh(); 
			return Result.success("系统配置删除成功");
		}else{
			GatewayCache.refresh(); 
			return Result.fail("系统配置失败");
		}
	}
	
	/**
	 * 刷新缓存
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/refreshConfig")
	@ResponseBody 
	public  Result  refreshConfig() throws Exception{
		MonitorAppCache.refresh();
		logger.info("缓存刷新成功");
		GatewayCache.refresh(); 
		DictCache.refreshCache();
		logger.info("交易后台缓存刷新成功");
		return Result.success("交易后台缓存刷新成功");
	}
	
	/**
	 * 获取session中的User
	 * @param req
	 * @return
	 */
	public static GatewayUser getSessionUser(HttpServletRequest req){
		HttpSession session = req.getSession();
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		return u;
	}
	/**
	 * 刷新所有的界面出单系统缓存 如：http://www.locahost.com;http://119.179.0.19:8080
	 * @param req
	 * @return
	 * author 王雁
	 * 
	 * date 2015年5月8日17:32:09
	 */
	@RequestMapping(value="/refreshFacadeCaches")
	public @ResponseBody Map<String,Object> refreshFacadeCaches(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		
		String urls = GatewayCache.getCache(Constants.REFRESH_CACHE_URLS);
		if(urls==null||"".equals(urls)){
			map.put("result", "empty");
			map.put("message", "请添加界面出单url,用参数名：<a style=\"color:red;\">"+Constants.REFRESH_CACHE_URLS+"</a>,<br>如有多个，请用英文;分割.");
		}else{
			List<Map<String,String>> errorUrls = new ArrayList<Map<String,String>>();
			String [] rulsArray = urls.split(";");
			for (String realUrl : rulsArray) {
				Map<String,String> urlMap=new HashMap<String,String>();
				String response = "";
				BufferedReader in = null;
				try {
					URL url = new URL(realUrl);
					URLConnection urLConnection = url.openConnection();
					urLConnection.setConnectTimeout(5000);//设置请求超时
					in = new BufferedReader(new InputStreamReader(urLConnection.getInputStream()));
					String inputLine = "";
					while((inputLine = in.readLine()) != null){
						response += inputLine;
					}
					if(!response.contains("\"type\":\"success\"")){
						urlMap.put("url", realUrl);
						errorUrls.add(urlMap);
					}
				} catch (Exception e) {
					urlMap.put("url", realUrl);
					errorUrls.add(urlMap);
					logger.info("界面出单系统缓存刷新失败");
					logger.info(e);
				} finally{
					if(in != null){
						try {
							in.close();
						} catch (IOException e) {
							logger.info(e);
						}
					}
				}	
			}
			if(errorUrls.size()>0){
				map.put("result", "fail");
				map.put("data", errorUrls);
			}else{
				map.put("result", "success");
				map.put("message", "界面出单系统缓存刷新成功");
			}
			
		}
		return map;
	}
}
